<template>
  <view class="edit-form px-4 py-2 bg-gray-100 min-h-screen">
    <!-- 基础资料 -->
    <view class="bg-white rounded-lg mb-4">
      <view class="text-lg font-bold px-4 py-3 border-b border-gray-100"> 基础资料 </view>

      <view class="divide-y divide-gray-100">
        <view class="flex justify-between items-center px-4 py-3" @tap="handleItemTap('昵称')">
          <text class="text-gray-700">昵称</text>
          <view class="flex items-center">
            <input
              :value="memberStore.profile?.nickName"
              @input="nickNameChange($event)"
              class="text-gray-400 mr-2"
            />
          </view>
        </view>
        <view class="flex justify-between items-center px-4 py-3">
          <text class="text-gray-700">出生日期</text>
          <view class="flex items-center">
            <uni-datetime-picker
              type="date"
              v-model="memberStore.profile!.birthday"
              start="1950-1-1"
              @change="changeBirthday"
            />
            <!-- <text class="text-gray-400 mr-2">{{ memberStore.profile?.age }}</text> -->
          </view>
        </view>
        <view class="flex justify-between items-center px-4 py-3" @tap="handleItemTap('身高')">
          <text class="text-gray-700">身高</text>
          <view class="flex items-center">
            <text class="text-gray-400 mr-2">{{ memberStore.profile?.height }}cm</text>
            <text class="text-gray-300">></text>
          </view>
        </view>

        <view class="flex justify-between items-center px-4 py-3">
          <text class="text-gray-700">居住城市</text>
          <view class="flex items-center">
            <uni-data-picker
              v-model="memberStore.profile!.cityCode"
              @change="onCityChange"
              :localdata="addressStore.selectedAddress"
              class="w-full"
            ></uni-data-picker>
          </view>
        </view>
        <view class="flex justify-between items-center px-4 py-3">
          <text class="text-gray-700">家乡</text>
          <view class="flex items-center">
            <uni-data-picker
              v-model="memberStore.profile!.homeCityCode"
              @change="onHomeCityChange"
              :localdata="addressStore.selectedAddress"
              class="w-full"
            ></uni-data-picker>
          </view>
        </view>

        <view class="flex justify-between items-center px-4 py-3" @tap="handleItemTap('感情状态')">
          <text class="text-gray-700">感情状态</text>
          <view class="flex items-center">
            <text class="text-gray-400 mr-2">{{ memberStore.profile?.emotional }}</text>
            <text class="text-gray-300">></text>
          </view>
        </view>

        <view class="flex justify-between items-center px-4 py-3" @tap="handleItemTap('婚姻状况')">
          <text class="text-gray-700">婚姻状况</text>
          <view class="flex items-center">
            <text class="text-gray-400 mr-2">{{ memberStore.profile?.marriage }}</text>
            <text class="text-gray-300">></text>
          </view>
        </view>
        <view class="flex justify-between items-center px-4 py-3" @tap="handleItemTap('脱单目标')">
          <text class="text-gray-700">脱单目标</text>
          <view class="flex items-center">
            <text class="text-gray-400 mr-2">{{ memberStore.profile?.loveGoal }}</text>
            <text class="text-gray-300">></text>
          </view>
        </view>
        <navigator
          url="/pages/school/school"
          open-type="navigate"
          hover-class="navigator-hover"
          class="flex justify-between items-center px-4 py-3"
        >
          <text class="text-gray-700">毕业院校</text>
          <view class="flex items-center">
            <text class="text-gray-400 mr-2">{{ memberStore.profile?.school }}</text>
            <text class="text-gray-300">></text>
          </view>
        </navigator>
        <view class="flex justify-between items-center px-4 py-3" @tap="handleItemTap('最高学历')">
          <text class="text-gray-700">最高学历</text>
          <view class="flex items-center">
            <text class="text-gray-400 mr-2">{{ memberStore.profile?.education }}</text>
            <text class="text-gray-300">></text>
          </view>
        </view>
        <view class="flex justify-between items-center px-4 py-3" @tap="handleItemTap('学历类型')">
          <text class="text-gray-700">学历类型</text>
          <view class="flex items-center">
            <text class="text-gray-400 mr-2">{{ memberStore.profile?.educationalType }}</text>
            <text class="text-gray-300">></text>
          </view>
        </view>
        <view class="flex justify-between items-center px-4 py-3" @tap="handleItemTap('职业')">
          <text class="text-gray-700">职业</text>
          <view class="flex items-center">
            <text class="text-gray-400 mr-2">{{ memberStore.profile?.profession }}</text>
            <text class="text-gray-300">></text>
          </view>
        </view>
        <view class="flex justify-between items-center px-4 py-3" @tap="handleItemTap('年薪')">
          <text class="text-gray-700">年薪</text>
          <view class="flex items-center">
            <text class="text-gray-400 mr-2">{{ memberStore.profile?.annualSalary }}</text>
            <text class="text-gray-300">></text>
          </view>
        </view>
        <view class="flex justify-between items-center px-4 py-3">
          <text class="text-gray-700">微信号</text>
          <view class="flex items-center">
            <input
              :value="memberStore.profile?.weChatNumber"
              @input="weChatNumberChange($event)"
              class="text-gray-400 mr-2"
              placeholder="仅作为紧急联系方式,不会暴露给用户"
            />
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import type { OptionsConfigType, ProfileUpdate } from '@/types/members'

import { useMemberStore } from '@/stores/modules/member'
import { useAddressStore } from '@/stores/modules/address'
import { onLoad } from '@dcloudio/uni-app'

import {
  statusOptions,
  marriageOptions,
  tuodanOptions,
  xueliOptions,
  xuelileixingOptions,
  zhiyeOptions,
  salaryOptions,
  shengaoOptions,
} from '@/types/constants'

const memberStore = useMemberStore()
const addressStore = useAddressStore()
onLoad(() => {
  addressStore.getArea()
})
// 居住城市
const onCityChange: UniHelper.UniDataPickerOnChange = (ev) => {
  if (ev.detail.value.length === 0) return
  //解构准备后端需要的数据code
  const [{ value: provinceCode }, { value: cityCode }] = ev.detail.value!

  // //对象的合并
  Object.assign(memberStore.profile!, { provinceCode, cityCode })
  memberStore.updateProfile(memberStore.profile!)
}
// 家乡
const onHomeCityChange: UniHelper.UniDataPickerOnChange = (ev) => {
  if (ev.detail.value.length === 0) return
  //解构准备后端需要的数据code
  const [{ value: homeProvinceCode }, { value: homeCityCode }] = ev.detail.value!

  // //对象的合并
  Object.assign(memberStore.profile!, { homeProvinceCode, homeCityCode })
  memberStore.updateProfile(memberStore.profile!)
}
//毕业院校
const schoolChange = () => {
  uni.navigateTo({
    url: '/pages/school/school',
  })
}
const changeBirthday: UniHelper.UniDatetimePickerOnChange = (ev) => {
  if (!ev) return
  console.log(ev)
  memberStore.profile!.birthday = ev.toString()
  memberStore.updateProfile(memberStore.profile!)
  // 更新用户信息
  memberStore.getUserMe()
}
// 防抖函数
const debounce = (fn: Function, delay: number) => {
  let timer: number | null = null
  return (...args: any[]) => {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(null, args)
    }, delay)
  }
}
// 通用的防抖更新函数
const updateProfile = debounce(() => {
  memberStore.updateProfile(memberStore.profile!)
}, 500)

const nickNameChange = (e: { detail: { value: string } }) => {
  if (!memberStore.profile) return
  memberStore.profile.nickName = e.detail.value
  // 更新昵称
  updateProfile()
}

const weChatNumberChange = (e: { detail: { value: string } }) => {
  if (!memberStore.profile) return
  memberStore.profile.weChatNumber = e.detail.value
  // 更新微信号
  updateProfile()
}

const optionsConfig: OptionsConfigType = {
  感情状态: {
    title: '请选择感情状态',
    options: statusOptions,
    field: 'emotional',
  },
  婚姻状况: {
    title: '请选择婚姻状况',
    options: marriageOptions,
    field: 'marriage',
  },
  脱单目标: {
    title: '请选择脱单目标',
    options: tuodanOptions,
    field: 'loveGoal',
  },
  最高学历: {
    title: '请选择最高学历',
    options: xueliOptions,
    field: 'education',
  },
  学历类型: {
    title: '请选择学历类型',
    options: xuelileixingOptions,
    field: 'educationalType',
  },
  职业: {
    title: '请选择职业',
    options: zhiyeOptions,
    field: 'profession',
  },
  年薪: {
    title: '请选择年薪',
    options: salaryOptions,
    field: 'annualSalary',
  },
  身高: {
    title: '请选择身高',
    options: shengaoOptions,
    field: 'height',
  },
}
const handleItemTap = (item: string) => {
  const config = optionsConfig[item]
  if (config) {
    uni.showActionSheet({
      title: config.title,
      itemList: config.options.map((opt) => opt.label),
      success: (res) => {
        const index = res.tapIndex
        const value = config.options[index].label
        if (config.field) {
          //更新数据库
          const finalValue = config.field === 'height' ? parseInt(value) : value
          if (memberStore.profile && config.field in memberStore.profile) {
            ;(memberStore.profile[config.field as keyof ProfileUpdate] as typeof finalValue) =
              finalValue
            memberStore.updateProfile(memberStore.profile)
          }
        }
      },
    })
  }
}

// const basicInfo = ref({
//   nickName: '微信用户',
//   age: '25岁',
//   height: '140cm',
//   city: '深圳市',
//   emotional: '未知',
//   marriage: '未填写',
//   loveGoal: '匹配更精准，仅自己可见',
//   school: '北京航空航天大学',
//   education: '博士',
//   educationalType: '全日制',
//   profession: '公务员',
//   annualSalary: '未填写',
//   weChatNumber: '1234567890',
// })
</script>

<style scoped>
.edit-form {
  background-color: #f5f5f5;
}
</style>
